#pragma once
#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "Protocol.hpp"
#include "TcpServer.hpp"
#include "Log.hpp"
#include "ThreadPool.hpp"
#include "Task.hpp"

#define PORT 8081

class HttpServer{
    private:
        int port;
        bool stop;
    public:
        HttpServer(int _port = PORT)
            :port(_port)
            ,stop(false)
        {}
        void InitServer()
        {
            //为什么需要将SIGPIPE信号忽略呢?
            //将信号SIGPIPE进行忽略,如果不忽略,在写入的时候可能会直接崩溃
            signal(SIGPIPE,SIG_IGN);
        }

        void loop()
        {
            TcpServer* tsvr = TcpServer::getInstance(port);
            LOG(INFO,"loop begin...");
            while(!stop)
            {
               struct sockaddr_in peer;
               socklen_t len = sizeof(peer);
               //从已完成队列获取新连接,用于与客户端进行通信
               int sock = accept(tsvr->sock(),(struct sockaddr*)&peer,&len);
               if(len < 0)
               {
                   continue;
               }
               LOG(INFO,"Get a new link...");
               //创建任务
               Task task(sock);
               //将任务插入到任务队列中,交给线程池中的线程进行处理
               ThreadPool::GetInstance()->PushTask(task);
            }
        }

        ~HttpServer()
        {}
};
